package com.dawnling.androidutils.ui.scanner;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dawnling.androidutils.R;
import com.google.zxing.Result;
import com.gyf.barlibrary.ImmersionBar;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;

/**
 * 扫码页面 回调结果在调用扫码的界面
 */
public class ScannerActivity extends Activity implements
        DecoratedBarcodeView.TorchListener {

    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;
    private TextView switchFlashlightButton;
    private TextView tvTitle;
    public static final int REQUEST_CODE_PICK_IMAGE = 444;
    public static final int RESULT_CODE_PICK_IMAGE = 111;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scanner);

        ImmersionBar.with(this).transparentStatusBar().statusBarDarkFont(false).fitsSystemWindows(false).init();
        barcodeScannerView = findViewById(R.id.zxing_barcode_scanner);
        barcodeScannerView.setTorchListener(this);
        barcodeScannerView.setStatusText("");
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText(getResources().getString(R.string.scannerbar));

        switchFlashlightButton = findViewById(R.id.switch_flashlight);
        switchFlashlightButton.setText(getResources().getString(R.string.TurnOnTheLight));
        if (!hasFlash()) {
            switchFlashlightButton.setVisibility(View.GONE);
        }

        capture = new CaptureManager(this, barcodeScannerView);
        capture.initializeFromIntent(getIntent(), savedInstanceState);
        capture.decode();

        switchFlashlightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getResources().getString(R.string.TurnOnTheLight).equals(switchFlashlightButton.getText())) {
                    barcodeScannerView.setTorchOn();
                } else {
                    barcodeScannerView.setTorchOff();
                }
            }
        });

        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //识别相册二维码
        findViewById(R.id.tvPicture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        capture.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        capture.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        capture.onDestroy();
        ImmersionBar.with(this).destroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        capture.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }

    /**
     * Check if the device's camera has a Flashlight.
     *
     * @return true if there is Flashlight, otherwise false.
     */
    private boolean hasFlash() {
        return getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

    @Override
    public void onTorchOn() {
        switchFlashlightButton.setText(getResources().getString(R.string.TurnOffTheLight));
    }

    @Override
    public void onTorchOff() {
        switchFlashlightButton.setText(getResources().getString(R.string.TurnOnTheLight));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PICK_IMAGE:
                if (Activity.RESULT_OK == resultCode && null != data) {
                    Uri uri = data.getData();
                    ImageScanningTask scanningTask = new ImageScanningTask(uri,
                            new ImageScanningTask.ImageScanningCallback() {
                                @Override
                                public void onFinishScanning(Result result) {
                                    if (result != null) {
                                        Intent intent = new Intent();
                                        intent.putExtra("result", result.getText());
                                        LogUtils.e("ScannerActivity相册识别：" + result.getText());
                                        setResult(RESULT_CODE_PICK_IMAGE, intent);
                                        finish();
                                    } else {
                                        // 识别失败
                                        ToastUtils.showShort("识别失败");
                                    }
                                }
                            });
                    scanningTask.execute();
                } else {
                    // 什么也没有
                }
                break;
        }
    }
}
